package com.someok.utils.idgen;

import com.someok.utils.MathUtil;
import com.someok.utils.format.Format;

/**
 * Several UUID generators. Which one to use depends on destiantion
 * evironemnt. Generated UUIDs are not sequencial.
 * 
 * <p><a href="UuidGenerator.java.html"><i>View Source</i></a></p>
 *
 * @version $Revision: 41 $ $Date: 2006-06-27 23:17:14 +0800 (星期二, 27 六月 2006) $
 */
public class UuidGenerator {

	private final static String chars64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

	/**
	 * Returns unique String of 16 chars. This string is based on following template:
	 * 32bits from current time,
	 * 32bits from identityHashCode
	 * 32bits from random
	 * Total 96 bits, that are coded with base 6 so resulting string will
	 * have just 16 chars.
	 *
	 * @param o
	 *
	 * @return uuid as string of 16 chars
	 */
	public final static String generate(Object o) {
		long id1 = System.currentTimeMillis() & 0xFFFFFFFFL;
		long id2 = System.identityHashCode(o);
		long id3 = MathUtil.randomLong(-0x80000000L, 0x80000000L) & 0xFFFFFFFFL;

		id1 <<= 16;
		id1 += (id2 & 0xFFFF0000L) >> 16;
		id3 += (id2 & 0x0000FFFFL) << 32;

		return Format.convert(id1, 6, chars64) + Format.convert(id3, 6, chars64);
	}

	/**
	 * Returns just 10 random chars.
	 * Just based on current time and a random string.
	 *
	 * @return uuid string of 10 chars
	 * @see #generate(Object o)
	 */
	public final static String generate() {
		long id1 = System.currentTimeMillis() & 0x3FFFFFFFL;
		long id3 = MathUtil.randomLong(-0x80000000L, 0x80000000L) & 0x3FFFFFFFL;

		return Format.convert(id1, 6, chars64) + Format.convert(id3, 6, chars64);
	}
}
